package com.ruoyi.stock2.utils;

import com.ruoyi.stock2.thread.DownLoadThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

public class Sendmail {
    public static String sendEailWithExplanation = "0";
    public static String userAccout = "359642959@qq.com";
    public static String password = "zacmsfziegiebjei"; //imap邮箱密码 shbvyxjrsfqubghj  pop3邮箱密码 zacmsfziegiebjei
    public static Address[] address;
    public static Address[] addressbbc;
    public static String png, pdf, pdfDetails, explanation, content;

    public static String sb;

    private static final Logger log = LoggerFactory.getLogger(Sendmail.class);


    public static void main(String[] args)  throws Exception{
        address = new Address[1];
        addressbbc = new Address[1];
        for(int i = 0 ; i < 1 ; i++){
            try {
                address[i] = new InternetAddress("cn_wushu@163.com", "denishoh", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        for(int i = 0 ; i < 1 ; i++){
            try {
                addressbbc[i] = new InternetAddress("wushu02@sina.com", "denishoh", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        try {
            String strdate = OtherUtils.getLocalDateStr(new Date(),"yyyy-MM-dd");
            strdate = "2020-08-04";
            String png = "F:/profile/pdf_files/"+"stockForecastReference"+strdate+".png";
            String pdf = "F:/profile/pdf_files/"+"stockForecastReference"+strdate+".pdf";
            String pdfDetails = "F:/profile/pdf_files/"+"stockForecastReferenceDetails"+strdate+".pdf";
            String explanation = "F:/profile/pdf_files/explanation.pdf";
            //Sendmail.sendwithoutfujian();
            Sendmail.sendDownloadDataOK();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * @throws Exception
     */
    public static void send() throws Exception {
        sendmail();
    }

    public static void sendwithoutfujian() throws Exception {
        sendmailwithoutfujian();
    }

    public static void sendDownloadDataOK() throws Exception {
        sendmailwithoutfujian2();
    }

    public static void sendDownloadDataNew() throws Exception {
        sendmailwithoutfujian3();
    }

    public static void sendmail() throws Exception{
        //properties对象封装邮箱服务器配置
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        //props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.host", "smtp.qq.com");
        props.setProperty("mail.smtp.auth", "true");//需要密码认证
        Session session = Session.getInstance(props);
        //session.setDebug(true);
        //创建邮件
        Message msg = creatMessage(session);
        Transport transport = session.getTransport();
        transport.connect(userAccout,password);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
        log.warn("邮件发送完成");
    }

    public static void sendmailwithoutfujian() throws Exception{
        //properties对象封装邮箱服务器配置
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", "smtp.qq.com");
        props.setProperty("mail.smtp.auth", "true");//需要密码认证
        Session session = Session.getInstance(props);
        //session.setDebug(true);
        //创建邮件
        Message msg = creatMessagewithoutfujian(session);
        Transport transport = session.getTransport();
        transport.connect(userAccout,password);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

        log.warn("邮件发送完成");
    }

    public static void sendmailwithoutfujian2() throws Exception{
        //properties对象封装邮箱服务器配置
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", "smtp.qq.com");
        props.setProperty("mail.smtp.auth", "true");//需要密码认证
        Session session = Session.getInstance(props);
        //session.setDebug(true);
        //创建邮件
        Message msg = creatMessageDownloadDataOK(session);
        Transport transport = session.getTransport();
        transport.connect(userAccout,password);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
        log.warn("邮件发送完成");
    }

    public static void sendmailwithoutfujian3() throws Exception{
        //properties对象封装邮箱服务器配置
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", "smtp.qq.com");
        props.setProperty("mail.smtp.auth", "true");//需要密码认证
        Session session = Session.getInstance(props);
        //session.setDebug(true);
        //创建邮件
        Message msg = creatMessageDownloadDataNew(session);
        Transport transport = session.getTransport();
        transport.connect(userAccout,password);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
        log.warn("邮件发送完成");
    }
    //创建带图片和附件的邮件
    public static MimeMessage creatMessage(Session session) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(userAccout, "吴树", "UTF-8"));
        message.setRecipients(MimeMessage.RecipientType.TO, address);
        if(addressbbc.length > 0){
            message.setRecipients(MimeMessage.RecipientType.BCC, addressbbc);//密送
        }
        message.setSubject("股票预测报告 " + OtherUtils.getLocalDateStr(new Date(),"yyyy-MM-dd HH:mm:ss"), "UTF-8");
        //创建图片节点
        MimeBodyPart image = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource(png));
        image.setDataHandler(dh);
        image.setContentID("imageNum");
        //创建文本
        MimeBodyPart text = new MimeBodyPart();
        StringBuffer sm = new StringBuffer() ;
        sm.append("<ol>");
        sm.append("<li>文件 stockForecastReference.pdf 告诉我们哪一天行情开始好转 </li>");
        sm.append("<li>文件 stockForecastReferenceDetails.pdf 是未来40天的预测 </li>");
        sm.append("<li>文件 stockForecastReferenceDetails20daysAgo.pdf 20天之前结果 </li>");

        if("1".equals(sendEailWithExplanation)){
            sm.append("<li>文件 explanation.pdf 是使用说明 </li>");
        }
        sm.append("</ol>");
        text.setContent("<img src='cid:imageNum' /><br>"+sm, "text/html;charset=utf-8"); //注意编码问题
        //设置文本和图片的联系
        MimeMultipart mm_text_image = new MimeMultipart();
        mm_text_image.addBodyPart(image);
        mm_text_image.addBodyPart(text);
        mm_text_image.setSubType("related");//关联关系
        //把上面的Multipart放在BodyPart中
        MimeBodyPart text_image = new MimeBodyPart();
        text_image.setContent(mm_text_image);

        //创建附件节点
        MimeBodyPart attachment1 = new MimeBodyPart();
        DataHandler dh1 = new DataHandler(new FileDataSource(pdf));
        attachment1.setDataHandler(dh1);
        attachment1.setContentID("pdf1");
        String[] nstr1 = pdf.split("/");
        attachment1.setFileName(nstr1[nstr1.length-1]);

        MimeBodyPart attachment2 = new MimeBodyPart();
        DataHandler dh2 = new DataHandler(new FileDataSource(pdfDetails));
        attachment2.setDataHandler(dh2);
        attachment2.setContentID("pdf2");
        String[] nstr2 = pdfDetails.split("/");
        attachment2.setFileName(nstr2[nstr2.length-1]);

        MimeBodyPart attachment4 = new MimeBodyPart();
        String Details20daysAgo = pdfDetails.replace("Details","Details20daysAgo");
        DataHandler dh4 = new DataHandler(new FileDataSource(Details20daysAgo));
        attachment4.setDataHandler(dh4);
        attachment4.setContentID("pdf4");
        String[] nstr4 = Details20daysAgo.split("/");
        attachment4.setFileName(nstr4[nstr4.length-1]);


        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text_image);
        mm.addBodyPart(attachment1);
        mm.addBodyPart(attachment2);
        mm.addBodyPart(attachment4);
        if("1".equals(sendEailWithExplanation)){//判断是否发送使用说明
            MimeBodyPart attachment3 = new MimeBodyPart();
            DataHandler dh3 = new DataHandler(new FileDataSource(explanation));
            attachment3.setDataHandler(dh3);
            attachment3.setContentID("pdf3");
            String[] nstr3 = explanation.split("/");
            attachment3.setFileName(nstr3[nstr3.length-1]);
            mm.addBodyPart(attachment3);
        }

        mm.setSubType("related");
        message.setContent(mm);
        message.saveChanges();
        return message;
    }
    //创建带图片和附件的邮件
    public static MimeMessage creatMessagewithoutfujian(Session session) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(userAccout, "吴树", "UTF-8"));
        message.setRecipients(MimeMessage.RecipientType.TO, address);
        if(addressbbc.length > 0){
            message.setRecipients(MimeMessage.RecipientType.BCC, addressbbc);//密送
        }
        message.setSubject("股票预测报告 " + OtherUtils.getLocalDateStr(new Date(),"yyyy-MM-dd HH:mm:ss"), "UTF-8");

        //创建文本
        MimeBodyPart text = new MimeBodyPart();
        StringBuffer sm = new StringBuffer() ;
        //<html><body><input type='text' value='123456'>茶叶</input></body></html>
        sm.append("<h3>没有统计出结果</h3><br>");
        if("1".equals(sendEailWithExplanation)){
            sm.append("文件 explanation.pdf 是参考说明");
        }
        text.setContent(sm.toString(), "text/html;charset=utf-8"); //注意编码问题
        //设置文本和图片的联系
        MimeMultipart mm_text_image = new MimeMultipart();
        mm_text_image.addBodyPart(text);
        mm_text_image.setSubType("related");//关联关系
        //把上面的Multipart放在BodyPart中
        MimeBodyPart text_image = new MimeBodyPart();
        text_image.setContent(mm_text_image);
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text_image);
        if("1".equals(sendEailWithExplanation)){//是否含有使用说明
            MimeBodyPart attachment3 = new MimeBodyPart();
            DataHandler dh3 = new DataHandler(new FileDataSource(explanation));
            attachment3.setDataHandler(dh3);
            attachment3.setContentID("pdf3");
            String[] nstr3 = explanation.split("/");
            attachment3.setFileName(nstr3[nstr3.length-1]);
            mm.addBodyPart(attachment3);
        }
        mm.setSubType("related");
        message.setContent(mm);
        message.saveChanges();
        return message;
    }

    //发送新版
    public static MimeMessage creatMessageDownloadDataNew(Session session) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(userAccout, "吴树", "UTF-8"));
        message.setRecipients(MimeMessage.RecipientType.TO, address);
        if(addressbbc.length > 0){
            message.setRecipients(MimeMessage.RecipientType.BCC, addressbbc);//密送
        }
        message.setSubject("统计报告 " + OtherUtils.getLocalDateStr(new Date(),"yyyy-MM-dd HH:mm:ss"), "UTF-8");

        //创建文本
        MimeBodyPart text = new MimeBodyPart();
        StringBuffer sm = new StringBuffer() ;
        //<html><body><input type='text' value='123456'>茶叶</input></body></html>
        sm.append(sb);

        text.setContent(sm.toString(), "text/html;charset=utf-8"); //注意编码问题
        //设置文本和图片的联系
        MimeMultipart mm_text_image = new MimeMultipart();
        mm_text_image.addBodyPart(text);
        mm_text_image.setSubType("related");//关联关系
        //把上面的Multipart放在BodyPart中
        MimeBodyPart text_image = new MimeBodyPart();
        text_image.setContent(mm_text_image);
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text_image);

        mm.setSubType("related");
        message.setContent(mm);
        message.saveChanges();
        return message;
    }

    //下载一天数据
    public static MimeMessage creatMessageDownloadDataOK(Session session) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(userAccout, "吴树", "UTF-8"));
        message.setRecipients(MimeMessage.RecipientType.TO, address);
        if(addressbbc.length > 0){
            message.setRecipients(MimeMessage.RecipientType.BCC, addressbbc);//密送
        }
        message.setSubject("股票下载报告 " + OtherUtils.getLocalDateStr(new Date(),"yyyy-MM-dd HH:mm:ss"), "UTF-8");

        //创建文本
        MimeBodyPart text = new MimeBodyPart();
        StringBuffer sm = new StringBuffer() ;
        //<html><body><input type='text' value='123456'>茶叶</input></body></html>
        sm.append("<h3>下载完成</h3><br>");

        text.setContent(sm.toString(), "text/html;charset=utf-8"); //注意编码问题
        //设置文本和图片的联系
        MimeMultipart mm_text_image = new MimeMultipart();
        mm_text_image.addBodyPart(text);
        mm_text_image.setSubType("related");//关联关系
        //把上面的Multipart放在BodyPart中
        MimeBodyPart text_image = new MimeBodyPart();
        text_image.setContent(mm_text_image);
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text_image);

        mm.setSubType("related");
        message.setContent(mm);
        message.saveChanges();
        return message;
    }

    public static String formatSubjectForDetail(String subject) throws UnsupportedEncodingException{
        subject = subject.replaceAll("\r", "").replaceAll("\n", "");

        if(subject.toUpperCase().contains("=?UTF-8?Q?")) {
            String[] subjectParts = subject.split("\\s+");
            StringBuffer returnSubject = new StringBuffer("=?UTF-8?Q?");
            for(String part : subjectParts) {
                if(part.length()>12) {
                    returnSubject.append(part.substring(10, part.length()-2));
                }else {
                    returnSubject.append(part);
                }

            }
            returnSubject.append("?=");
            return MimeUtility.decodeText(returnSubject.toString());

        }
        if(subject.startsWith("=?")) {
            String[] subjectParts = subject.split("\\s+");
            StringBuffer returnSubject = new StringBuffer();
            for(String part : subjectParts) {
                if(part.toUpperCase().contains("CN-GB")){
                    part = part.replaceAll("CN-GB", "GB2312");
                }
                returnSubject.append( MimeUtility.decodeText(part) );
            }
            return returnSubject.toString();
        }

        return subject;

    }

}
